import _config from "./_config";
import _string from "../utils/_string";
import cache_user from "../cache/cache_user";
import cache_token from "../cache/cache_token";
let _router = {

    //注册路由函数
    _register_rule : function (path) {

        //去除间隔符
        const component = _string.trim_separator(path, '/')

        let rule = {}
        //访问地址
        rule.path = _config.prefix + path
        //页面地址
        rule.component = (resolve) => require([`../views/${component}`], resolve)
        //规则
        return rule
    },

    //注册动态路由
    _register_rule_404: function (){
        return { path: '*', redirect: _config.prefix + '/notice/error' }
    },

    //身份校验 - 管理员
    auth_manage: function () {
        if (cache_user.empty() || cache_token.empty()) {
            this.jmp_url('/manage/index')
        }

        this.is_manage()
    },

    //身份校验 - 商家
    auth_business: function () {
        if (cache_user.empty() || cache_token.empty()) {
            this.jmp_url('/business/index')
        }

        this.is_business()
    },

    //权限验证
    auth_role: function (rids){
        if (cache_user.empty())
            return this.jmp_error('身份过期，请重新登录')

        const user = cache_user.get()
        for (let i in rids.split(',')) {
            if (rids[i] == user.rid) {
                return true
            }
        }

        return this.jmp_error('权限不足')
    },

    //是否管理员
    is_manage: function (){
        if (cache_user.empty())
            return this.jmp_error('身份过期，请重新登录')

        const user = cache_user.get()
        if (user.rid < 11) {
            return true
        }

        return this.jmp_error('权限不足')
    },

    //是否商家
    is_business: function (){
        if (cache_user.empty())
            return this.jmp_error('身份过期，请重新登录')

        const user = cache_user.get()
        if (user.rid > 10) {
            return true
        }

        return this.jmp_error('权限不足')
    },

    jmp_url: function (url) {
        window.location.href = _config.prefix +  url
    },

    jmp_success:function (msg) {
        window.location.href = _config.prefix +  '/notice/success?msg=' + msg
    },

    jmp_error:function (msg) {
        window.location.href = _config.prefix +  '/notice/error?msg=' + msg
    },

};


export default _router;
